package com.integral.system.position.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.integral.common.domain.R;
import com.integral.system.position.domain.CfgPositionIntegralDo;
import com.integral.system.position.service.CfgPositionIntegralService;
import com.integral.utils.ExcelHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

@Controller
@RequestMapping("/position")
public class CfgPositionIntegralController {

    private static final String FUN_NAME = "" ;//功能名称,建议英文,中文可能有问题

    @Autowired
    private CfgPositionIntegralService positionService;

    //分页查询
    @GetMapping("")
    @ResponseBody
    public PageInfo<CfgPositionIntegralDo> page(@RequestParam(required = false) Map<String,Object> params){
        QueryWrapper<CfgPositionIntegralDo> queryWrapper = new QueryWrapper<>();
        Integer pageNum = null;
        Integer pageSize = null;
        if (ObjectUtil.isNotEmpty(params)){
            for (String key : params.keySet()) {
                if ("pageNum".equals(key) || "pageSize".equals(key)){
                    continue;
                }
                queryWrapper.like(key,params.get(key));
            }

            pageNum = Integer.parseInt((String) params.get("pageNum"));
            pageSize = Integer.parseInt((String) params.get("pageSize"));
        }

        pageNum = pageNum == null? 1:pageNum;
        pageSize = pageSize == null?10: pageSize;

        PageHelper.startPage(pageNum,pageSize);

        List<CfgPositionIntegralDo> list = positionService.list(queryWrapper);
        return new PageInfo<>(list);
    }

    // 根据条件查询(不分页)
    public List<CfgPositionIntegralDo> selectBy(Map<String,Object> params){
        QueryWrapper<CfgPositionIntegralDo> queryWrapper = new QueryWrapper<>();
        if (ObjectUtil.isNotEmpty(params)){
            for (String key : params.keySet()) {
                if ("pageNum".equals(key) || "pageSize".equals(key)){
                    continue;
                }
                queryWrapper.like(key,params.get(key));
            }
        }
        List<CfgPositionIntegralDo> list = positionService.list(queryWrapper);
        return list;
    }

    //新增
    @PostMapping("")
    @ResponseBody
    public R add(@RequestBody CfgPositionIntegralDo positionIntegralDo){
        QueryWrapper<CfgPositionIntegralDo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("position_name",positionIntegralDo.getPositionName());
        List<CfgPositionIntegralDo> list = positionService.list(queryWrapper);
        if (list.size() > 0){
            return R.error("当前职务已存在!");
        }
        boolean save = positionService.save(positionIntegralDo);
        return save ? R.ok(): R.error();
    }

    //修改
    @PutMapping("")
    @ResponseBody
    public R update(@RequestBody CfgPositionIntegralDo positionIntegralDo){
        boolean update = positionService.updateById(positionIntegralDo);
        return update? R.ok(): R.error();
    }

    //删除
    @DeleteMapping("")
    @ResponseBody
    public R remove(String id){
        boolean remove = positionService.removeById(id);
        return remove? R.ok(): R.error();
    }

    // 生成批量导入用的模板文件,生成路径在配置文件中配置
    @GetMapping("/getTemplateFile" )
    @ResponseBody
    public R getTemplateFile() {
        String templateFileName = ExcelHelper.generateTemplate(CfgPositionIntegralDo.class, FUN_NAME);
        return R.ok().put("templateFileName", templateFileName);
    }

    //批量导入
    @PostMapping("/importData" )
    @ResponseBody
    public R importData(MultipartHttpServletRequest request) {
        //强转报错
        //MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        // 获得文件：
        MultipartFile tempUploadFile = request.getFile("fileData" ); //FIXME 【重要】参数名需要换掉??
        if (null == tempUploadFile) {
            return R.error("未读取到文件信息" );
        }
        String orgName = tempUploadFile.getOriginalFilename();
        String extName = FileUtil.extName(orgName);
        // (?!)表示整体忽略大小写, $表示字符串结尾
        String pattern = "(?i)(xlsx)$";
        if (!Pattern.matches(pattern, extName)) {
            return R.error("上传文件必须是xlsx类型");
        }

        List<CfgPositionIntegralDo> list = ExcelHelper.parseUploadData(tempUploadFile, CfgPositionIntegralDo.class);
        if (null != list && list.size() > 0) {
            boolean saveResult = false;
            try {
                saveResult = positionService.saveBatch(list);
                if (saveResult) {
                    return R.ok();
                } else {
                    return R.error("批量导入失败，入库失败！" );
                }
            } catch (Exception e) {
                e.printStackTrace();
                return R.error("批量导入失败，服务器异常！" );
            }

        } else {
            return R.error("批量导入失败，读取文件内容为空！" );
        }
    }

    // 批量导出
    @PostMapping("/getExportFile" )
    @ResponseBody
    public R getExportFile(@RequestBody(required = false) Map<String, Object> params) {
        List<CfgPositionIntegralDo> list = this.selectBy(params);
        String exportFileName = ExcelHelper.generateExportFile(list, FUN_NAME, CfgPositionIntegralDo.class);
        if (null != exportFileName) {
            return R.ok().put("exportFileName", exportFileName);
        } else {
            return R.error("批量导出失败" );
        }
    }

    // 下载文件
    @PostMapping("/downloadFile/{fileName}" )
    public void downloadFile(HttpServletRequest request, HttpServletResponse response, @PathVariable(name = "fileName" ) String fileName) {
        ExcelHelper.downloadExcelFile(request, response, fileName);
    }

    // 查询职务列表字典
    @GetMapping("/getPositionDict")
    @ResponseBody
    public R getPositionDict(){
        QueryWrapper<CfgPositionIntegralDo> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("position_no","position_name");
        List<CfgPositionIntegralDo> list = positionService.list(queryWrapper);
        return R.ok().put("list",list);
    }

}
